package com.example.boot.netty;

import io.netty.channel.Channel;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Description: 用户id和channel的关联关系处理
 */
public class UserChannelRel {
	private static final HashMap<String, Channel> manager = new HashMap<>();

	public static void put(String senderId, Channel channel) {
		manager.put(senderId, channel);

	}

	
	public static Channel get(String senderId) {
		return manager.get(senderId);
	}
	public static void remove(String senderId) {

	//	String channelId = ctx.channel().id().asShortText();
		Iterator<HashMap.Entry<String, Channel>> it = manager.entrySet().iterator();
		while (it.hasNext()) {
			HashMap.Entry<String, Channel> entry = it.next();
			String sid=	entry.getValue().id().asLongText();
			System.out.println("UserId: " + entry.getKey()
					+ ", ChannelId: " + entry.getValue().id().asLongText());
if (senderId.equals(sid)){
	manager.remove(entry.getKey());
}
		}

	}
	public static void output() {
		System.out.println("在线用户数： "+manager.size()+" 个");
		for (HashMap.Entry<String, Channel> entry : manager.entrySet()) {
			System.out.println("UserId: " + entry.getKey() 
							+ ", ChannelId: " + entry.getValue().id().asLongText());
		}
	}
	public static HashMap<String, Channel> getUserChannelRel(){
		return manager;
	}

	public static void removeChannel(Channel channel) {
		manager.entrySet();

		Iterator<HashMap.Entry<String, Channel>> it = manager.entrySet().iterator();
		while (it.hasNext()) {
			HashMap.Entry<String, Channel> entry = it.next();
			System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
			String senderId=	entry.getValue().id().asLongText();
			String sid=	channel.id().asLongText();
			if (senderId.equals(sid)){
				manager.remove(entry.getKey());
			}
		}

		/*for (HashMap.Entry<String, Channel> entry : manager.entrySet()) {

			System.out.println("UserId: " + entry.getKey()
					+ ", ChannelId: " + entry.getValue().id().asLongText());
			String senderId=	entry.getValue().id().asLongText();
			String sid=	channel.id().asLongText();
			if (senderId.equals(sid)){
				manager.remove(entry.getKey());
			}
		}*/

	}
}
